package com.example.jucdemo.synchdemo;

/**
 * @Author: Dijah
 * @Date: 2023/3/17 15:54
 * @Desc:
 * 场景： 两个线程同时访问同一个对象的不同的同步方法
 */
public class demo6 implements Runnable {

    static demo6 instance1 = new demo6();
    static demo6 instance2 = new demo6();

    @Override
    public void run() {
        if(Thread.currentThread().getName().equals("Thread-0")){
            method1();
        }
        if(Thread.currentThread().getName().equals("Thread-1")){
            method0();
        }
    }

    private synchronized static void method0() {
        System.out.println("thead name ： " + Thread.currentThread().getName() + ",start" );
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("thread name : " + Thread.currentThread().getName() + ",end");
        method1();
    }

    private synchronized static void method1() {
        System.out.println("thead name ： " + Thread.currentThread().getName() + ",start" );
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("thread name : " + Thread.currentThread().getName() + ",end");
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(instance1);
        Thread thread2 = new Thread(instance1);
        thread1.start();
        thread2.start();
        while (thread1.isAlive() || thread2.isAlive()){
        }
        System.out.println("test over ");
    }
}
